<template>
  <div class="index">
    <nav-header
      :headerTitle="'BWRM'"
      :navBgColor="'#fff'"
      :isNext="false"
      :isNavBack="false"
      :isNedMsg="true"
      :msgNum="headerMsgNum"
    ></nav-header>
    <div class="content fix_iphonex_margin">
      <div class="swiper">
        <task-course-swiper :swiperData="swiperData"></task-course-swiper>
      </div>
      <div class="task-horn">
        <div class="money-left">
          <div class="horn"></div>
          <div class="horn-text">让你的BWRM你赚钱</div>
        </div>
        <div class="money-right">
          <div class="money-count">今日已赚：{{amountToday}}元</div>
        </div>
      </div>
      <div class="task-progress">
        <task-progress :pageName="'taskIndex'" :taskProStatus="taskProStatus"></task-progress>
      </div>
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        <div class="task-list">
          <!-- @load="getFlowHomeTask" -->
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="getFlowHomeTask"
            :error.sync="error"
            error-text="请求失败，点击重新加载"
            :offset="offsetIndex"
          >
            <!-- @getAdId="getAdId" -->
            <task-list-item
              v-for="(item, index) of taskList"
              :key="'tl' + index"
              :listItem="item"
              :pageName="'taskIndex'"
              :transmitState="transmit"
              @acquireTask="clickTaskBtn"
              @tapToDetail="clickTapToDetail"
              :indexDisabled="indexDisabled"
            ></task-list-item>
          </van-list>
        </div>
        <div class="empty"></div>
      </van-pull-refresh>
    </div>
    <nav-footer></nav-footer>
    <ModalCopy :ModalCopy.sync="ModalCopy" @ModalCopyClick="copyClick"></ModalCopy>
  </div>
</template>

<script type="text/ecmascript-6">
import mixin from '@/utils/mixin'
import NavHeader from '@/components/NavHeader'
import TaskCourseSwiper from '@/components/TaskCourseSwiper'
import TaskProgress from '@/components/TaskProgress'
import TaskListItem from '@/components/TaskListItem'
import NavFooter from '@/components/NavFooter'
import ModalCopy from "@/components/ModalCopy";
import { Dialog, List, PullRefresh } from 'vant'

Vue.use(List).use(PullRefresh)

export default {
  name: 'infIndex',
  mixins: [mixin],
  data () {
    return {
      headerMsgNum: 0,
      uniqueId: '',
      swiperData: [],
      taskList: [],
      taskProStatus: {},
      amountToday: 0,
      transmit: 0,
      currentAdId: 0,
      ModalCopy: {},
      // 监听滚动数据
      pageNum: 1,
      pageSize: 10,
      finished: false,
      loading: false,
      error: false,
      // 滚动条到底部距离
      offsetIndex: 0,
      indexDisabled: false,
      isLoading: false,
    }
  },
  created () {
    this.$setgoindex();
    this.getBannerList()
    this.getWxAdmin()
    this.getOffsetIndex()

  },
  activated () {
    this.getTodayAmountAndTaskStatus()
    // // 保存改变的taskList
    let that = this
    // console.log(this)
    this.$http.post('/flowForward/getTaskInfoByForwardId', {
      uniqueId: this.uniqueId,
      adId: this.currentAdId
    }).then(
      res => {
        let resData = res.data
        that.saveUpdatedTaskList(resData)
      },
      err => {
        console.log(err)
      }
    )
  },
  mounted () {

    // 流量主获取 App-uid
    let query = this.$route.query;
    if (query.uniqueId) {
      if (query.uniqueId != 0) {
        window.localStorage.setItem("uniqueIdByInfluencer", query.uniqueId);
        let aduniqueId = query.aduniqueId ? ((query.aduniqueId == 0 || query.aduniqueId == '0') ? "" : query.aduniqueId) : "";
        window.localStorage.setItem("uniqueId", aduniqueId);
      } else {
        window.localStorage.setItem("uniqueIdByInfluencer", null);
        window.localStorage.removeItem("uniqueIdByInfluencer");
      }
    }
    window.localStorage.setItem("platformRole", 2);

    if ((window.localStorage.getItem("uniqueIdByInfluencer"))) {
      // 网页获取App消息数量
      let parmars_bri = { uniqueId: query.uniqueId };
      this.$bridge.callHandler("getMsgNumByWeb", parmars_bri, res => {
        this.headerMsgNum = parseInt(res);
      });
    } else {
      this.headerMsgNum = 0;
    }
    // app主动推送给消息条数给网页
    this.$bridge.registerHandler("pushMsgNumByApp", (data, responseCallback) => {
      // data为ObjC传递给JS的数据
      this.headerMsgNum = data;
      // js返回数据给Objc
      responseCallback('success')
    });
    sessionStorage.setItem('activeName', '0')
    this.getUniqueId()
    this.getTodayAmountAndTaskStatus();
    // console.log(this)
  },

  // 组件内守卫
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    if (!['taskDetail', 'taskCourse'].includes(to.name)) {
      // 删除当前组件的缓存
      if (this.$vnode && this.$vnode.data.keepAlive) {
        if (this.$vnode.parent && this.$vnode.parent.componentInstance && this.$vnode.parent.componentInstance.cache) {
          if (this.$vnode.componentOptions) {
            let key = this.$vnode.key == undefined
              ? this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${this.$vnode.componentOptions.tag}` : '')
              : this.$vnode.key;
            let cache = this.$vnode.parent.componentInstance.cache;
            let keys = this.$vnode.parent.componentInstance.keys;
            if (cache[key]) {
              if (keys.length) {
                let index = keys.indexOf(key);
                if (index > -1) {
                  keys.splice(index, 1);
                }
              }
              delete cache[key];
            }
          }
        }
      }
    }
    next()
  },
  methods: {
    // 路由缓存处理
    changeKeepAlive (name, keepAlive) {
      // @ts-ignore
      // console.log(this.$router)
      this.$route.matched.map((item) => {
        if (item.name === name) {
          item.meta.keepAlive = keepAlive
          console.log(item.meta.keepAlive)
        }
      })
    },

    // 下拉刷新
    onRefresh () {
      setTimeout(() => {
        // this.$toast('刷新成功');
        this.pageNum = 1
        this.taskList = []
        this.finished = false
        this.loading = false
        this.error = false
        this.getTodayAmountAndTaskStatus()
        this.getFlowHomeTask()
        this.isLoading = false;
      }, 500);
    },
    // 获取流量主用户Id
    getUniqueId () {
      if (this.isNull(window.localStorage.getItem('uniqueIdByInfluencer'))) {
        this.uniqueId = ""
      } else {
        this.uniqueId = window.localStorage.getItem('uniqueIdByInfluencer')
      }
    },
    // 获取当前点击的任务的广告Id
    // getAdId (id) {
    //   this.currentAdId = id
    // },
    // 滚动条到底部距离
    getOffsetIndex () {
      let fonts = window.document.body.style.fontSize
      let fontSize = fonts.split('px')[0]
      this.offsetIndex = 500 / 37.5 * fontSize
    },
    // 获取管理员微信号
    getWxAdmin () {
      this.$http.post('/soft/getWapConfig', {}).then(
        res => {
          let wapConfig = res.data;
          this.ModalCopy = {
            isModal: false,
            title: '您还不是流量主，暂时无法接任务。请先添加微信管理员，开通流量主权限。',
            name: `微信号：${wapConfig.adminWxNum}`,
            copy: wapConfig.adminWxNum,
            rightBtn: '复制微信号'
          }
        },
        err => {
          console.log(err)
        }
      )
    },
    // 获取轮播图广告图片
    getBannerList () {
      this.$http.post('/banner/getBannerList', {
        // 流量主首页参数是7
        bannerLocation: 7
      }).then(
        res => {
          let resData = res.data
          // console.log(resData)
          this.swiperData = resData
        },
        err => {
          console.log(err)
        }
      )
    },
    // 获取流量主广场任务列表
    getFlowHomeTask () {
      this.$http.post('ad/getFlowHomeTask', {
        uniqueId: this.uniqueId,
        pageSize: this.pageSize,
        pageNum: this.pageNum,
      }).then(
        res => {
          let resData = res.data
          this.taskList = this.taskList.concat(resData.items)
          ++this.pageNum
          this.loading = false
          if (resData.pages < this.pageNum) {
            this.finished = true
          }
        },
        err => {
          this.error = true
          console.log(err)
        }
      )
    },
    // 获取今日收益和任务状态
    getTodayAmountAndTaskStatus () {
      this.$http.post('/flowForward/getTodayAmountAndTaskStatus', {
        uniqueId: this.uniqueId
      }).then(
        res => {
          let resData = res.data
          this.amountToday = resData.amountMap.AmountToday / 100
          this.taskProStatus = resData.statusMap
          // this.setTaskProStatus(this.taskProStatus)
        },
        err => {
          console.log(err)
        }
      )
    },
    // 复制微信号
    copyClick () {
      this.copy('.btn')
    },
    // 点击任务按钮实现功能方法
    clickTaskBtn (currentAdId) {
      this.getUniqueId()
      this.currentAdId = currentAdId
      this.$http.post('/flowForward/getTaskInfoByForwardId', {
        uniqueId: this.uniqueId,
        adId: currentAdId
      }).then(
        res => {
          let resData = res.data
          sessionStorage.setItem('taskItemString', JSON.stringify(resData))
          sessionStorage.setItem('adIdByInfluencer', resData.id)
          if (resData.forwardAuditStatus === undefined && resData.adLaunchStatus === 1) {
            this.getTakeTask(currentAdId)
          } else {
            // this.saveUpdatedTaskList(resData)
            if ([2, 4, 5, 6].includes(resData.forwardAuditStatus)) {
              this.$router.push({
                path: '/infMine/msgState',
                query: {
                  inuniqueId: this.uniqueId,
                  adId: currentAdId
                }
              })
            } else {
              this.$router.push({
                path: '/infIndex/taskCourse',
                query: {
                  inuniqueId: this.uniqueId,
                  adId: currentAdId
                }
              })
            }
          }
        },
        err => {
          console.log(err)
        }
      )
    },
    // 点击任务内容进入详情
    clickTapToDetail (currentAdId) {
      this.getUniqueId()
      this.currentAdId = currentAdId
      this.getUniqueId()
      this.$http.post('/flowForward/getTaskInfoByForwardId', {
        uniqueId: this.uniqueId,
        adId: currentAdId
      }).then(
        res => {
          let resData = res.data
          // this.saveUpdatedTaskList(resData)
          sessionStorage.setItem('taskItemString', JSON.stringify(resData))
          sessionStorage.setItem('adIdByInfluencer', currentAdId)
          // 跳转到任务详情页面
          this.$router.push({
            path: '/infIndex/taskDetail',
            query: {
              inuniqueId: this.uniqueId,
              adId: currentAdId
            }
          })
        },
        err => {
          console.log(err)
        }
      )
    },
    // 拷贝改变的item，保存被改变的taskList
    saveUpdatedTaskList (keepAliveItem) {
      this.taskList.forEach(item => {
        if (item.id === keepAliveItem.id) {
          let index = this.taskList.indexOf(item)
          this.taskList.splice(index, 1, keepAliveItem)
        }
      })
    },
    // 接任务接口
    getTakeTask (currentAdId) {
      console.log(this.uniqueId)
      console.log(currentAdId)
      // this.indexDisabled = true
      if (!this.uniqueId) {
        // 未登录
        Dialog.confirm({
          message: '您还没有登录，请先登录',
          confirmButtonText: '登录'
        }).then(() => {
          window.sessionStorage.setItem("appKey" , null) ;
          window.sessionStorage.setItem("jmsz" , null) ;  
          window.sessionStorage.removeItem("appKey");
          window.sessionStorage.removeItem("appKejmszy");
          debugger
          this.$router.replace('/infLogin/login');
        }).catch(() => {
          return false
        })
        return false
      }
      this.$http.post('/flowForward/takeTask', {
        uniqueId: this.uniqueId,
        adId: currentAdId
      }).then(
        res => {

          // this.indexDisabled = false
          let headData = res.head
          let takeTaskCode = headData.code

          if (takeTaskCode === 124) {
            // 尚未完善资料
            Dialog.confirm({
              message: '您尚未完善资料',
              confirmButtonText: '去完善'
            }).then(() => {
              this.goUrl('/infLogin/improveInfo')
            }).catch(() => {
              return false
            })
          } else if (takeTaskCode === 176) {
            // 领任务超过了10条
            Dialog.alert({
              message: 'Hi,您今天已经完成了10条任务了，明天再来接任务赚钱吧。',
              confirmButtonText: '确定'
            }).then(() => {
              return false
            })
          } else if (takeTaskCode === 177) {
            // 任务不能重复领取
            Dialog.alert({
              message: '亲，任务不能重复领取',
              confirmButtonText: '确定'
            }).then(() => {
              return false
            })
          } else if (takeTaskCode === 178) {
            // 任务被领取完
            Dialog.alert({
              message: '对不起，该任务已经被领取完毕 请确定重新刷新后查看可接任务',
              confirmButtonText: '刷新任务'
            }).then(() => {
              window.location.reload();
            })
          } else if (takeTaskCode === 179) {
            // 未加管理员微信号弹窗
            this.ModalCopy.isModal = true
          } else if (takeTaskCode === 180) {
            let msgAdid = headData.msg.split(',')[0]
            console.log(msgAdid)
            sessionStorage.setItem('adIdByInfluencer', msgAdid)
            // 还有未提交任务
            Dialog.alert({
              message: '您还有任务未上传图片哦',
              confirmButtonText: '确定'
            }).then(() => {
              this.$router.push({
                path: '/infIndex/taskCourse',
                query: {
                  inuniqueId: this.uniqueId,
                  adId: msgAdid
                }
              })
            })
          } else if (takeTaskCode === 200) {
            // 任务领取成功
            this.$router.push({
              path: '/infIndex/taskCourse',
              query: {
                inuniqueId: this.uniqueId,
                adId: currentAdId
              }
            })

          }
        },
        err => {
          console.log(err.data.head)
        }
      )
    },
  },
  components: {
    NavHeader,
    TaskCourseSwiper,
    TaskProgress,
    TaskListItem,
    NavFooter,
    ModalCopy
  }
}
</script>

<style scoped lang="scss">
@import '~@/assets/css/common.scss';
.index {
  width: 100%;
  height: 100%;
  padding: 0 32px;
  box-sizing: border-box;
  & /deep/ .ModalCopy {
    padding: 0;
  }
  & /deep/ .ModalCopy .divOne {
    padding: 0 30px;
    box-sizing: border-box;
    text-align: left;
  }
  .content {
    width: 100%;
    margin-top: 112px;
    .swiper {
      width: 686px;
      height: 300px;
      border-radius: 16px;
      // background: #ccc;
      margin-bottom: 24px;
      overflow: hidden;
    }
    .task-horn {
      width: 686px;
      height: 60px;
      background: rgba(237, 237, 237, 1);
      border-radius: 8px;
      position: relative;
      display: flex;
      margin-bottom: 24px;
      .money-left {
        flex: 1;
        .horn {
          position: absolute;
          top: 16px;
          left: 16px;
          width: 30px;
          height: 28px;
          background: url('../../../assets/images/home_notice.png') center /
            contain no-repeat;
        }
        .horn-text {
          height: 60px;
          font-size: 26px;
          font-family: PingFangSC-Regular;
          font-weight: 400;
          color: rgba(48, 49, 51, 1);
          line-height: 60px;
          margin-left: 62px;
        }
      }
      .money-right {
        flex-basis: 250px;
        height: 60px;
        background: rgba(255, 231, 231, 1);
        border-radius: 0px 8px 8px 0px;
        @include center;
        .money-count {
          height: 60px;
          font-size: 26px;
          font-family: PingFangSC-Medium;
          font-weight: 500;
          color: rgba(255, 37, 37, 1);
          line-height: 60px;
        }
      }
    }
  }
  .empty {
    height: 98px;
  }
}
</style>
